import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os

# 读取轮廓图
silhouette_path = r'E:\datasets\2.Gait3D\2D_Silhouettes\0000\camid0_videoid2\seq0\human_crop_f11675.png'
silhouette = mpimg.imread(silhouette_path)

# 检查轮廓图是否加载正确
plt.imshow(silhouette, cmap='gray')
plt.title('Check Silhouette Image')
plt.show()

# 读取关键点数据
def read_keypoints(file_path):
    keypoints = {}
    if not os.path.exists(file_path):
        print(f"File not found: {file_path}")
        return keypoints

    with open(file_path, 'r') as f:
        lines = f.readlines()
        print("File content preview:", lines[:5])  # 输出文件的前几行，查看文件格式
        for line in lines:
            parts = line.strip().split(',')
            if len(parts) % 3 == 0:  # 确保每行是3的倍数（x, y, confidence）
                for i in range(0, len(parts), 3):
                    try:
                        x, y = float(parts[i]), float(parts[i+1])
                        name = f"keypoint_{len(keypoints)}"  # 给每个关键点命名
                        keypoints[name] = (x, y)
                    except ValueError:
                        print(f"Skipping invalid line: {line}")
    return keypoints

# 关键点文件路径
keypoints_path = r'E:\datasets\2.Gait3D\2D_Poses\0000\camid0_videoid2\seq0\human_crop_f11675.txt'
keypoints = read_keypoints(keypoints_path)

# 检查关键点数据是否正确读取
if not keypoints:
    print("No keypoints loaded. Check the file format and path.")
else:
    print("Loaded keypoints:", keypoints)

# 打印所有关键点坐标，以便检查是否存在异常
for name, (x, y) in keypoints.items():
    print(f"Keypoint: {name}, x: {x}, y: {y}")

# 翻转 y 轴，使关键点方向匹配图像
img_height = silhouette.shape[0]
for name in keypoints:
    x, y = keypoints[name]
    keypoints[name] = (x, img_height - y)

# 检查关键点是否在图像内
for name, (x, y) in keypoints.items():
    if not (0 <= x < silhouette.shape[1] and 0 <= y < silhouette.shape[0]):
        print(f"Warning: Keypoint '{name}' is outside the image bounds: ({x}, {y})")

# 创建图像
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# 显示轮廓图
ax1.imshow(silhouette, cmap='gray')
ax1.set_title('Silhouette')
ax1.axis('off')

# 绘制骨架图
ax2.set_xlim(0, silhouette.shape[1])
ax2.set_ylim(0, silhouette.shape[0])
ax2.set_title('Skeleton')
ax2.axis('off')
ax2.invert_yaxis()  # 确保 y 轴方向匹配图像

# 绘制简化版本的几个关键点
simplified_keypoints = list(keypoints.keys())  # 使用所有读取到的关键点
for name in simplified_keypoints:
    if name in keypoints:
        x, y = keypoints[name]
        ax2.scatter(x, y, color='black', s=30, edgecolors='white', zorder=3)
        ax2.text(x + 5, y, name, fontsize=8, color='black')

# 调整布局
plt.tight_layout()
plt.show()
